package com.amigo.online.common.base.controller;

import com.amigo.online.common.core.json.JsonObjectMapper;
import com.amigo.online.common.core.response.Response;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.util.StringUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.List;

public abstract class BaseConsumerController {
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	private final JsonObjectMapper objectMapper = new JsonObjectMapper();
	
	/** 设置成功响应代码 */
    protected ResponseEntity<Response> success() {
        return setResponse(StatusCode.OK, true, StatusCode.OK.msg(), null);
    }
    /** 设置成功响应代码 */
    protected ResponseEntity<Response> success(Object data) {
        return setResponse(StatusCode.OK, true, StatusCode.OK.msg(), data);
    }

    /** 设置失败响应代码 */
    protected ResponseEntity<Response> failure() {
        return setResponse(StatusCode.BAD_REQUEST, false, StatusCode.BAD_REQUEST.msg(), null);
    }
    /** 设置失败响应代码 */
    protected ResponseEntity<Response> failure(StatusCode code) {
        return setResponse(code, false, code.msg(), null);
    }
    
    /**
     * 响应报文
     * @param code 状态码
     * @param success 是否成功
     * @param message 消息
     * @param data 数据
     * @return 响应实体
     */
    protected ResponseEntity<Response> setResponse(StatusCode code, boolean success, String message, Object data) {
        return setResponse(code.value(), success, message, data);
    }
    protected ResponseEntity<Response> setResponse(int code, boolean success, String message, Object data) {
        return ResponseEntity.ok(new Response(code, success, message, data));
    }
	// 封装参数方法
    @SuppressWarnings("rawtypes")
	protected Object getDto(HttpServletRequest request, Class clazz) {
        try {
        	String method = request.getMethod();
        	String param = null;
        	if("GET".equals(method.toUpperCase())) {
        		param= request.getParameter("param");
                param = URLDecoder.decode(param, "UTF-8");
        	}else {
        		BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        		param = IOUtils.toString(reader);
        		
        	}
        	if (StringUtils.startsWith(param, "[") && StringUtils.endsWith(param, "]")) {
                return objectMapper.readValue(param, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
            }
            return objectMapper.fromJsonString(param, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
